﻿using System;
using System.Collections.Generic;
using System.Linq;
using TuxedoLib;

namespace SpaceSquirrel
{
	public class DialogScene : GameSceneBase
	{
		private static string[] d(params string[] lines) {
			return lines;
		}

		private static string[][] s(params string[][] stanzas) {
			return stanzas;
		}

		private static readonly Dictionary<string, string[][]> DIALOGS = new Dictionary<string, string[][]>()
		{
			{ "Feeder1", s(d(
				"Quick, collect seeds",
				"before anyone notices!")) },

			{ "Feeder2", s(d(
				"Uh-oh, your covert",
				"attempt has failed!",
				"Quick, make a getaway!")) },
			
			{ "WaterDone", s(d(
				"That's the last of the",
				"reservoirs. Receiving",
				"Transmission from the",
				"General..."),
		
				d(
				"We have a small hiccup;",
				"the seeds intended to",
				"provide vegetation were",
				"accidentally left here."),

				d("Fortunately, a vanguard",
				"of our sworn enemies is",
				"north of your location",
				"bearing their own seeds."),

				d("You can simultaneously",
				"stop their invasion and",
				"steal their seeds for",
				"our own purposes."),

				d("It's a case of killing",
				"two birds with one",
				"stone! Or anything else",
				"you might prefer.")) },
	
			{ "GravityDone", s(d(
				"The gravity emitter is",
				"now taking effect."),
		
				d("You can now hold B to",
				"run and jump."),
		
				d("Running jumps reach",
				"higher spots."),
		
				d("Head back to the ship",
				"for further instructions",
				"from the General.")) },
			{ "Open1", s(d(
				"An intrepid explorer",
				 "left home in search of",
				 "a better life for all",
				 "squirrelkind."),
		
				d("Bearing the hopes and",
				"dreams of her people,",
				"the squirrel set course",
				"for a nearby moon.")) },
			
			{ "Open2", s(d(
				"Her vessel reaches the",
				"moon laden with large",
				"supply stores as well as",
				"terraforming equipment"),
		
				d("...including the very",
				"latest in hydration",
				"technology:"),
		
				d("Giant water balloons.")) },
			
			{ "Open3", s(d(
				"As she gazes upon the",
				"barren waste of the",
				"desolate moon, she",
				"says to herself:"),
		
				d("`I've got a lot of",
				"work to do.\"")) },

			{ "Volcano", s(d(
				"That's the last of the",
				"volcanoes."),
		 
				d("Now that the magnetic",
				"field is back, the",
				"atmosphere will",
				"re-accumulate.")) },
	
			{ "T1", s(d(
				"Hello explorer! We trust",
				"your journey was a",
				"pleasant one."),

				d("Your first task is to",
				"normalize the gravity on",
				"the moon."),
	
				d("Place the gravity",
				"emitter within the",
				"moon's core."),
	
				d("Remember we're relying",
				"on you; don't forget the",
				"`gravity\" of our",
				"situation!")) },
	
	
			{ "T2", s(d(
				"Now in order to restore",
				"the moon's magnetic",
				"field, you'll need some",
				"specialized equipment."),

				d("Take your packet of",
				"Acme Instant Lava and",
				"sprinkle a little into",
				"inactive volcanoes."),
		
				d("Presto, lava! And as",
				"everyone knows, lava",
				"creates magnetic fields."),

				d("SCIENCE!")) },
	
			{ "T3", s(d(
				"When you landed, your",
				"H2O reservoirs should",
				"have been released."),
		
				d("You will need to break",
				"the rubber coating on",
				"the reservoirs to",
				"release the water.")) },
	
			{"T4", s(
				d("We have a small hiccup;",
				"the seeds intended to",
				"provide vegetation were",
				"accidentally left here."),

				d("Fortunately, a vanguard",
				"of our sworn enemies is",
				"heading to your location",
				"bearing their own seeds."),

				d("You can simultaneously",
				"stop their invasion and",
				"steal their seeds for",
				"our own purposes."),

				d("It's a case of killing",
				"two birds with one",
				"stone! Or anything else",
				"you might prefer.")) },
			

			{ "CloseDialog", s(
				d("Congratulations!",
				"The Space Squirrel has",
				"managed to bring life",
				"to this once dead moon."),
		 
				d("Now her people have a",
				"beautiful new home, and",
				"it's all thanks to you!")) },
		};

		private int stanzaIndex = 0;
		private double textCursor = 0;
		private bool blink = false;

		private GameSceneBase bg;
		private bool storyMode;
		private bool forceArrow;
		private int delayCounter;
		private string[][] stanzas;
		private string[] activeStanza;
		private List<Image> showLines;
		private string id;

		private Pair<int, int> generalLoc;

		public DialogScene(GameSceneBase bg, string dialogId, bool slightDelay, bool storyMode, bool forceArrow)
		{
			this.bg = bg;
			this.storyMode = storyMode;
			this.forceArrow = forceArrow;
			if (bg is PlayScene)
			{
				Sprite player = ((PlayScene)bg).Player;
				player.moving = false;
				player.lastDirection = "left";
			}
			this.delayCounter = slightDelay ? 45 : 0;
			this.stanzas = DIALOGS[dialogId];
			this.showLines = new List<Image>();
			this.id = dialogId;
			this.generalLoc = null;
			if (dialogId.Length == 2 && dialogId[0] == 'T')
			{
				this.generalLoc = new Pair<int, int>(4 * 16, 6 * 16);
			}
		}

		public override void ProcessInput(List<MyEvent> events, Dictionary<string, bool> pressedActions)
		{
			if (this.blink)
			{
				foreach (MyEvent ev in events)
				{
					if (ev.Down && (ev.Action == "A" || ev.Action == "B" || ev.Action == "start"))
					{
						this.stanzaIndex++;
						this.textCursor = 0;
					}
				}
			}
			else
			{
				if (pressedActions["A"] || pressedActions["B"] || pressedActions["start"])
				{
					if (this.delayCounter < 0)
					{
						this.textCursor += 1.2;
					}
				}
			}
		}

		public override void Update()
		{
			if (this.bg.Flags.Contains('M'))
			{
				((PlayScene)this.bg).PlayMusic();
			}

			this.delayCounter--;
			if (this.stanzaIndex >= this.stanzas.Length)
			{
				this.Next = this.bg;
				this.bg.Next = this.bg;
			}
			else
			{
				this.activeStanza = this.stanzas[this.stanzaIndex];
				string rawLines = string.Join("\n", this.activeStanza);
				this.blink = false;
				int cursor = (int)this.textCursor;
				if (cursor >= rawLines.Length)
				{
					this.blink = true;
				}
				else
				{
					rawLines = rawLines.Substring(0, cursor);
				}
				string[] showLinesStr = rawLines.Split('\n');
				this.showLines.Clear();
				foreach (string line in showLinesStr)
				{
					if (line.Length > 0)
					{
						this.showLines.Add(Text.Render(-1, line));
					}
				}
			}

			if (this.delayCounter < 0)
			{
				this.textCursor += 0.3;
			}
		}

		private static readonly string[] generalPicker = new string[] { "", "1", "2", "3" };

		public override void Render(TuxedoLib.Image screen, int renderCounter)
		{
			this.bg.Render(screen, renderCounter);

			if (this.delayCounter > 0)
			{
				return;
			}

			if (this.generalLoc != null)
			{
				string path = "tiles/screen-static/screen" + generalPicker[(renderCounter / 4) & 3] + ".png";
				screen.Blit(ImageLibrary.GetImage(path), this.generalLoc.First, this.generalLoc.Second);
			}

			if (!this.storyMode)
			{
				SquirrelUtil.DrawBox(screen, 16, 16, 28, 9);
			}

			int x = 32;
			int y = 32;
			int space = 8;
			if (this.storyMode)
			{
				y += 16 * 7;
				space = 16;
			}
			int startY = y;
			foreach (Image line in this.showLines)
			{
				screen.Blit(line, x, y);
				y += space;
			}
			if (this.blink && ((renderCounter / 7) & 1) == 0)
			{
				int posX = 256 - 40;
				int posY = startY + space * 4;
				if (!this.forceArrow && this.stanzaIndex == this.stanzas.Length - 1)
				{
					Draw.RectangleFill(screen, -1, posX, posY, 8, 8);
				}
				else
				{
					screen.Blit(Text.Render(-1, "^"), posX, posY);
				}
			}

			if (!this.blink && (renderCounter % 5 == 0))
			{
				SoundManager.PlayNoise("text_char");
			}
		}
	}
}
